package com.landiao.ctrler;

import java.io.Serializable;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.landiao.common.factory.ResultMsgFactory;
import com.landiao.common.pojo.Page;
import com.landiao.common.pojo.Querier;
import com.landiao.common.pojo.ResultMsg;
import com.landiao.common.utils.CodecUtils;
import com.landiao.mybatis.plugin.ReflectHelper;
import com.landiao.service.BaseService;

/**
 * 增删改查control
 * 
 */
public abstract class BaseCRUDCtrler<T,PK extends Serializable> extends BaseCtrler{

	protected BaseService<T, PK> baseService;
	
	 /**
     * 实体类型
     */
    protected final Class<T> entityClass;
	
	 public BaseCRUDCtrler() {
		super();
		this.entityClass = ReflectHelper.findParameterizedType(getClass(), 0);
	}

	/**
     * 设置基础service
     *
     * @param baseService
     */
    @Autowired
    public void setBaseService(BaseService<T, PK> baseService) {
        this.baseService = baseService;
    }
    
    @RequestMapping("index")
	public String index(Model model) {
		return viewName("index");
	}
	
	@ResponseBody
	@RequestMapping("page")
	public Page<T> page(T t,Querier querier){
		this.setCompId(t);
		Page<T> page = baseService.queryByPage(querier,t);
		return page;
	}

	@RequestMapping(value = "add", method = RequestMethod.GET)
	public String add(Model model) {
		return viewName("add");
	}
	
	@RequestMapping(value = "edit/{id}", method = RequestMethod.GET)
	public String edit(Model model,@PathVariable PK id) {
		T t = baseService.getById(id);
		model.addAttribute("t",t);
		return viewName("edit");
	}
	
	@RequestMapping(value = "save")
	public String save(T t,RedirectAttributes redirectAttr) {
		try{
			this.setEntityId(t);
			this.setCompId(t);
			ReflectHelper.setValueByFieldName(t,"stateDate",new Date());
			baseService.save(t);
			redirectAttr.addFlashAttribute("resultMsg",
					ResultMsgFactory.success("添加成功"));
		}catch(Exception e){
			e.printStackTrace();
			log.error("添加失败：{}",e.getMessage());
			redirectAttr.addFlashAttribute("resultMsg",
					ResultMsgFactory.fail("添加失败"));
		}
		return redirectToUrl(viewName("index"));
	}
	
	@RequestMapping(value = "update")
	public String update(T t,RedirectAttributes redirectAttr) {
		try{
			baseService.update(t);
			redirectAttr.addFlashAttribute("resultMsg",
					ResultMsgFactory.success("修改成功"));
		}catch(Exception e){
			e.printStackTrace();
			log.error("修改失败：{}",e.getMessage());
			redirectAttr.addFlashAttribute("resultMsg",
					ResultMsgFactory.fail("修改失败"));
		}
		return redirectToUrl(viewName("index"));
	}
	
	@ResponseBody
	@RequestMapping(value = "delete/{id}", method = RequestMethod.POST)
	public ResultMsg delete(@PathVariable PK id) {
		try{
			baseService.delete(id);
			return ResultMsgFactory.success("删除成功");
		}catch(Exception e){
			e.printStackTrace();
			log.error("删除失败：{}",e.getMessage());
			return ResultMsgFactory.success("删除失败");
		}
	}

	
	@ResponseBody
	@RequestMapping(value = "batch/delete", method = {RequestMethod.GET, RequestMethod.POST})
	public ResultMsg batchDel(@RequestParam(value = "ids", required = false) PK[] ids) {

//		baseService.delete(ids);还未实现
		return ResultMsgFactory.success("批量删除成功");
	}
	
	/**
	 * 主键赋值,默认赋值属性:类名字（首字母小写）Id，例：backstageUserId
	 * 若格式不一致，需继承自己实现
	 * @param t
	 */
	protected void setEntityId(T t){
		String str = this.entityClass.getSimpleName();
		String fieldName = str.replaceFirst(str.substring(0, 1),str.substring(0, 1).toLowerCase())+"Id";
		ReflectHelper.setValueByFieldName(t,fieldName,CodecUtils.getUUID());
	}
	
	/**
	 * 企业id赋值,默认赋值属性:compId
	 * @param t
	 */
	protected void setCompId(T t){
		ReflectHelper.setValueByFieldName(t,"compId",this.getClientUser().getUser().getCompId());
	}
}
